﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;

namespace MVCApplication.Helpers
{
    public class DataSetHelper
    {
        public static object GetComboDescription(string rowFilterExpression, DataView dataView, string comboDescriptionColumn)
        {
            AppendRowFilterExpression(rowFilterExpression, dataView);
            if (dataView.Count == 1)
            {
                return dataView[0][comboDescriptionColumn];
            }
            else
            {
                return null;
            }
        }

        public static void AppendRowFilterExpression(string rowFilterExpression, DataView dataView)
        {
            string rowFilterToAdd = dataView.RowFilter;
            if (!string.IsNullOrEmpty(rowFilterToAdd))
            {
                rowFilterToAdd += " AND ";
            }
            rowFilterToAdd += rowFilterExpression;
            dataView.RowFilter = rowFilterToAdd;
        }

        public static void SetRowValue(DataRow dr, string colName, string strValue)
        {
            Type colDataType = dr.Table.Columns[colName].DataType;
            if (strValue == "" && dr.Table.Columns[colName].AllowDBNull)
            {
                dr[colName] = Convert.DBNull;
            }
            else if (colDataType.Equals(typeof(System.Int16)))
            {
                dr[colName] = System.Int16.Parse(strValue);
            }
            else if (colDataType.Equals(typeof(System.Double)))
            {
                dr[colName] = System.Double.Parse(strValue);
            }
            else if (colDataType.Equals(typeof(System.DateTime)))
            {
                dr[colName] = System.DateTime.Parse(strValue);
            }
            else if (colDataType.Equals(typeof(System.Int32)))
            {
                dr[colName] = System.Int32.Parse(strValue);
            }
            else if (colDataType.Equals(typeof(System.Decimal)))
            {
                dr[colName] = System.Decimal.Parse(strValue);
            }
            else if (colDataType.Equals(typeof(System.Int64)))
            {
                dr[colName] = System.Int64.Parse(strValue);
            }
            else if (colDataType.Equals(typeof(System.Boolean)))
            {
                dr[colName] = System.Boolean.Parse(strValue);
            }
            else if (colDataType.Equals(typeof(System.Guid)))
            {
                dr[colName] = new System.Guid(strValue);
            }
            else
            { //DkString 
                dr[colName] = strValue.TrimEnd();
            }

        }
    }
}
